package com.aiju.cash.ui.member;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.MemberApi;
import com.aiju.cash.core.api.MemberPointApi;
import com.aiju.cash.ui.member.adater.MemberCardAdapter;
import com.aiju.cash.ui.member.adater.MemberPointAdapter;
import com.aiju.cash.ui.member.entity.MemberCard;
import com.aiju.cash.ui.member.entity.Point;
import com.aiju.cash.util.GsonHelper;
import com.aiju.utils.L;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.loadmore.SwipeRefreshHelper;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2017-02-20 15:59
 * @version: V1.0
 * @Description: 会员首页 （会员卡列表）
 */
public class MemberCardActivity extends BaseTitleActivity implements View.OnClickListener {
    public static final int SELECT = 100;

    private int currentNum = 1;
    private int pageSize = 10;
    private View empty;

    private RecyclerView recyclerviewTeams;
    private SwipeRefreshLayout mSwipeRefreshLayout;

    private SwipeRefreshHelper mSwipeRefreshHelper;
    private RecyclerAdapterWithHF mAdapter;

    private List<MemberCard> memberCards = new ArrayList<>();
    private MemberCardAdapter mBlotterAdater;

    private boolean isLoad;
    private boolean isRefresh;

    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_member_card);
        type = getIntent().getIntExtra("type", 0);
        if (type == SELECT) {
            setCenterTitle("选择会员卡");
            findViewById(R.id.ly_member_bottom).setVisibility(View.GONE);
        } else {
            setCenterTitle("会员卡管理");
        }
        findViewById(R.id.ly_member_bottom).setOnClickListener(this);

        empty = findViewById(R.id.iv_empty);
        recyclerviewTeams = (RecyclerView) findViewById(R.id.recyclerview_member);
        recyclerviewTeams.setLayoutManager(new LinearLayoutManager(this));
        // recyclerviewTeams.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.sryt_swipe_listview);
        mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.app_title_color));
        mSwipeRefreshHelper = new SwipeRefreshHelper(mSwipeRefreshLayout);
        mSwipeRefreshHelper.setOnSwipeRefreshListener(new SwipeRefreshHelper.OnSwipeRefreshListener() {
            @Override
            public void onfresh() {
                L.d("onfresh");
                currentNum = 1;
                isRefresh = true;
                memberCards.clear();
                rquestMemberCardList();
            }
        });
        mSwipeRefreshHelper.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshHelper.loadMoreComplete(true);
                    return;
                }
                isLoad = true;
                ++currentNum;
                rquestMemberCardList();
            }
        });
        rquestMemberCardList();
    }

    @Override
    public void onBackPressed() {
        if (type == SELECT) {
            finish();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ly_member_bottom:
                goMemberCardAdd();
                break;
        }
    }

    /**
     * 会员卡列表
     */
    private void rquestMemberCardList() {
        mDialogHelper.showLoadingProgressDialog();
        L.d(String.valueOf(currentNum));
        new MemberApi().memberCardList(mUser.getStoreId(), mUser.getToken(), String.valueOf(currentNum),
                String.valueOf(pageSize), new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mDialogHelper.dismissProgressDialog();
                        T.ToastNetError();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        mDialogHelper.dismissProgressDialog();
                        DataJson json = new DataJson(response);
                        if (json.isSuccess()) {
                            List<MemberCard> cards = new Gson().fromJson(json.getData().toString(), new TypeToken<List<MemberCard>>() {
                            }.getType());
                            memberCards.addAll(cards);
                            setMemberCardsView();
                        } else {
                            T.ToastShort(json.getMsg());
                        }
                    }
                });
    }

    /**
     * 设置会员卡列表
     */
    private void setMemberCardsView() {
        if (mBlotterAdater == null) {
            mBlotterAdater = new MemberCardAdapter(this, memberCards, type);
            mAdapter = new RecyclerAdapterWithHF(mBlotterAdater);
            recyclerviewTeams.setVisibility(View.VISIBLE);
            recyclerviewTeams.setAdapter(mAdapter);
            mBlotterAdater.setOnItemClickListener(new MemberCardAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    if (type == SELECT) {
                        Intent intent = new Intent(MemberCardActivity.this, MemberAddActivity.class);
                        intent.putExtra("memberCard", memberCards.get(position));
                        setResult(RESULT_OK, intent);
                        finish();
                    } else {
                        goMemberCardInfoUser(position);
                    }
                }
            });
            isRefresh = true;
        } else {
            mBlotterAdater.notifyDataSetChanged();
        }

        //加载
        if (isLoad) {
            isLoad = false;
            mSwipeRefreshHelper.loadMoreComplete(true);
        }
        //刷新
        if (isRefresh) {
            isRefresh = false;
            mSwipeRefreshHelper.refreshComplete();
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }
        completeView();
    }

    /**
     * 加载完成视图动作
     */
    private void completeView() {
        //加载
        if (isLoad) {
            isLoad = false;
            mSwipeRefreshHelper.loadMoreComplete(true);
        }
        //刷新
        if (isRefresh) {
            isRefresh = false;
            mSwipeRefreshHelper.refreshComplete();
            mSwipeRefreshHelper.setLoadMoreEnable(true);
        }
        checkIfEmpty();
    }

    private void checkIfEmpty() {
        if (mBlotterAdater != null && mSwipeRefreshHelper != null) {
            final boolean emptyViewVisible = mBlotterAdater.getItemCount() == 0;
            if (emptyViewVisible) {
                //T.ToastShort("没有相关数据");
                empty.setVisibility(View.VISIBLE);
                recyclerviewTeams.setVisibility(View.GONE);
                mAiJuTitleBarView.getRightTextView().setVisibility(View.GONE);
            } else {
                empty.setVisibility(View.GONE);
                recyclerviewTeams.setVisibility(View.VISIBLE);
                mAiJuTitleBarView.getRightTextView().setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 会员卡详情
     */
    private void goMemberCardInfoUser(int position) {
        Intent intent = new Intent(this, MemberCardInfoActivity.class);
        intent.putExtra("memberCardId", memberCards.get(position).getId());
        startActivity(intent);
    }

    /**
     * 新建会员
     */
    private void goMemberAdd() {
        startActivity(MemberAddActivity.class);
    }

    /**
     * 新建会员卡
     */
    private void goMemberCardAdd() {
        startActivity(MemberCardAddActivity.class);
    }


}
